package org.ats.http;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.util.EntityUtils;
import org.ats.utils.HttpHelper;
import org.ats.utils.StringHelper;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * 未测试
 * */
public class ImageHttp extends AtsHttp {
	public static interface CallBackImageListener {
		public void CallBackImage(int actionId);
	}
	private String TAG ="ImageHttp";
	private Context mCm;
	private final int mActonId;
	private final String mlist[];
	private MessageDigest mDigest;
	private String imageFile = null;
	private SharedPreferences sp;
	private CallBackImageListener mlistener;
	public ImageHttp(Context context, int actionId, List<String> urlList) {
		mCm = context;
		mActonId = actionId;
		sp = PreferenceManager.getDefaultSharedPreferences(mCm);
		mlist = urlList.toArray(new String[urlList.size()]);
		try {
			mDigest = getMessageDigest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		running = true;
		while (running) {
			networkExchange();
		}
	}

	@Override
	void networkExchange() {
		try {
			ImageFilePathInit();
			String mTmp[] = mlist;
			for(String url:mTmp){
				mDigest.update(url.getBytes());
				final String cacheKey = StringHelper.bytesToHexString(mDigest.digest());
				File cacheFile = new File(imageFile,cacheKey);
				if(!cacheFile.exists()){
					final HttpClient httpClient = HttpHelper
							.getHttpClient(mCm
									.getApplicationContext());
					final HttpResponse resp = httpClient
							.execute(new HttpGet(url));
					final HttpEntity entity = resp.getEntity();

					final int statusCode = resp.getStatusLine()
							.getStatusCode();
					if (statusCode == HttpStatus.SC_OK
							|| entity != null) {
						final byte[] respBytes = EntityUtils.toByteArray(entity);
						updataRx(respBytes.length);
						if (cacheFile != null) {
							try {
								cacheFile.getParentFile().mkdirs();
								cacheFile.createNewFile();
								FileOutputStream fos = new FileOutputStream(
										cacheFile);
								fos.write(respBytes);
								fos.close();
							} catch (FileNotFoundException e) {
								Log.w(TAG,
										"Error writing to bitmap cache: "
												+ cacheFile.toString(),
										e);
							} catch (IOException e) {
								Log.w(TAG,
										"Error writing to bitmap cache: "
												+ cacheFile.toString(),
										e);
							}
						}
					}
				}
				
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			shutdown();
			PostCallBack();
		}

	}
	
	private void PostCallBack()
	{
		if(mlistener!=null){
			mlistener.CallBackImage(mActonId);
		}
	}
	
	private void ImageFilePathInit()
	{
		if (imageFile == null) {
			if (Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState())) {
				imageFile = Environment.getExternalStorageDirectory()
						+ File.separator + "Android" + File.separator
						+ "data" + File.separator + mCm.getPackageName()
						+ File.separator + "cache";
			}else {
				imageFile = mCm.getCacheDir().toString();
			}
		}
	}
	@Override
	void updataRx(int v) {
		long n = sp.getLong("ih-rx", 0);
		sp.edit().putLong("ih-rx", n+v).commit();
	}

	@Override
	public long getRx(int v) {
		return sp.getLong("ih-rx", 0);
	}

	@Override
	void updataTx(int v) {
		long n = sp.getLong("ih-tx", 0);
		sp.edit().putLong("ih-tx", n+v).commit();
	}

	@Override
	public long getTx(int v) {
		return sp.getLong("ih-tx", 0);
	}

	@Override
	void setHeader(HttpRequestBase hrb) {

	}
	public void setCallBackImageListener(CallBackImageListener Listener) {
		mlistener = Listener;
	}

}
